#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

int main(int argc, char* argv[]) {
    if (argc != 3) {
        cerr << "用法: ./client <服务器IP> <端口号>" << endl;
        return 1;
    }

    const char* serverIP = argv[1];  // 从命令行参数获取服务器IP
    int port = atoi(argv[2]);        // 从命令行参数获取端口号

    int sockfd;
    struct sockaddr_in serverAddr;
    char buffer[1024];

    // 创建TCP socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket() failed");
        return 1;
    }

    // 设置服务器地址
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(port);
    serverAddr.sin_addr.s_addr = inet_addr(serverIP);  // 使用命令行传入的IP地址

    // 连接服务器
    if (connect(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        perror("connect() failed");
        return 1;
    }

    cout << "连接到服务器: " << serverIP << "，端口: " << port << endl;

    // 发送请求
    string message;
    cout << "请输入英文单词: ";
    while (cin >> message) {
        write(sockfd, message.c_str(), message.length());

        // 读取服务器返回的翻译
        int bytesRead = read(sockfd, buffer, sizeof(buffer) - 1);
        buffer[bytesRead] = '\0';  // 添加字符串终止符
        cout << "服务器回复: " << buffer << endl;
        
        cout << "请输入英文单词: ";
    }

    close(sockfd);
    return 0;
}
